/**
 * Created with hong.rong
 * Description:eventEmitter hook
 * Date:2020/06/29
 */

import { useRef, useEffect } from 'react'

export class EventEmitter {
  subscriptions = new Map()
  emit = (eventName, val) => {
    if (this.subscriptions.has(eventName)) {
      this.subscriptions.get(eventName)(val)
    }
  }

  useSubscription = (eventName, callback) => {
    const callbackRef = useRef()
    callbackRef.current = callback
    useEffect(() => {
      function subscription(val) {
        if (callbackRef.current) {
          callbackRef.current(val)
        }
      }
      this.subscriptions.set(eventName, subscription)
      return () => {
        this.subscriptions.delete(eventName)
      }
    }, [eventName])
  }
}

export default function useEventEmitter() {
  if (!window.MXEventEmitter) {
    window.MXEventEmitter = new EventEmitter()
  }
  return window.MXEventEmitter
}
